﻿var IdentityType = new function () {
    'use strict';

    this.getIdentityType = el => {
        var identity = {
            id: 'identityId',
            name: 'identityName',
            $field: undefined
        };

        identity.$field = el.$form.find('[data-field="identityName"]');
        if (!$.com.isJqueryObject(identity.$field)) {
            identity.id = 'ownerId';
            identity.name = 'ownerName';
            identity.$field = el.$form.find('[data-field="ownerName"]');
        }

        return identity;
    }

    this.onEditOpened = el => {
        el.$el.find('[data-field="identityType"]').change();
        var identity = IdentityType.getIdentityType(el);
        if ($.com.isJqueryObject(identity.$field)) {
            identity.$field.data(_config_.field.namespace).refresh();
        }
    }

    this.onIdentityTypeChange = el => {
        var identity = IdentityType.getIdentityType(el);
        if ($.com.isJqueryObject(identity.$field)) {
            var field = identity.$field.data(_config_.field.namespace);
            if ($.com.hasValue(field)) {
                var popupType = "SelectUser";
                var identityType = el.options.value.firstUpperCase();
                switch (identityType) {
                    case "User":
                    case "Role":
                    case "Group":
                    case "Level":
                        popupType = "Select" + identityType;
                        break;
                    default:
                        popupType = null;
                        break;
                }

                if (popupType) {
                    field.display(true);
                    if (field.options.popup != popupType) {
                        field.options.popup = popupType;
                        field.reset();
                    }

                    //重新初始化 popup
                    var popup = identity.$field.data(_config_.popup.namespace);
                    if (popup) {
                        popup.options.popup = popupType;
                        popup.init();
                    }
                } else {
                    field.display(false);
                }
            }
        }
    }

    this.onGridSelecting = (el, event, data) => {
        if ($.com.hasValue(data)) {
            var identity = IdentityType.getIdentityType(el);
            if (data.identityType && $.com.hasValue(identity.id) && (data.identityType == 'User' || data.identityType == 'Role' || data.identityType == 'Group' || data.identityType == 'Level')) {
                let url = `/api/${data.identityType}s?$select=id,name,alias&$filter=id eq '${data[identity.id]}'`;
                $.api.get(url, false, x => {
                    x = x.rows || x;
                    if ($.com.isArray(x) && x.length === 1) {
                        data[identity.name] = x[0].alias;
                    }
                });
            }
        }
    }
}